import { get } from 'lodash-es'

export function checkCondition(leftValue, rightVale, conditionConfig) {
  const { type, conditionsType } = conditionConfig;
  // 如果条件值不存在，则不满足条件
  if (
      rightVale === undefined ||
      rightVale === null ||
      leftValue === undefined ||
      leftValue === null
  ) {
    return false;
  }
  // 如果是number类型,传入的值无法转为数字
  if (type === 'NUMBER' && isNaN(Number(rightVale))) {
    return false;
  }

  switch (conditionsType) {
    case 'contain': // 包含
    case 'LIKE':
      return String(leftValue).indexOf(rightVale) > -1;
    case 'notContain': // 不包含
    case 'UNLIKE':
      return String(leftValue).indexOf(rightVale) === -1;
    case 'empty': // 为空
    case 'EMPTY':
      return !leftValue;
    case 'notEmpty': // 非空
    case 'NOT_EMPTY':
      return !!leftValue;
    case 'startWith': // 开头是
      return String(leftValue).startsWith(rightVale);
    case 'notStartWith': // 开头不是
      return !String(leftValue).startsWith(rightVale);
    case 'endWith': // 结尾是
      return String(leftValue).endsWith(rightVale);
    case 'notEndWith': // 结尾不是
      return !String(leftValue).endsWith(rightVale);
    case 'GT': // 大于
      return leftValue > rightVale;
    case 'LT': // 小于
      return leftValue < rightVale;
    case 'EQ': // 等于
      return leftValue === rightVale;
    case 'NE': // 不等于
      return leftValue !== rightVale;
    case 'GE': // 大于等于
      return leftValue >= rightVale;
    case 'LE': // 小于等于
      return leftValue <= rightVale;
    default:
      return false;
  }
  return true;
}
export function checkCommonCondition(conditions, formState, dataConnector) {
  if (!conditions || conditions.length === 0) {
    return true;
  }
  return conditions.every((conditionItem) => {
    const { linkageFormFieldId, conditionsType, type, currentValue } = conditionItem;
    return checkCondition(get(dataConnector, linkageFormFieldId), get(formState, currentValue), {
      type,
      conditionsType,
    });
  });
}

export function getResultByCurrentCommonCondition(conditions, formState, dataConnector) {
  let result = {};
  for (const item of dataConnector) {
    if (checkCommonCondition(conditions, formState, item)) {
      result = item;
      return item;
    }
  }
}
